//
//  nbViewController.m
//  shifaOASystem
//
//  Created by michael on 2017/10/13.
//  Copyright © 2017年 czd. All rights reserved.
//

#import "nbViewController.h"
#import "detailViewController.h"
#import "yjTableViewCell.h"
#import "dzTableViewCell.h"
#import "GDataDefines.h"
#import "UnDoneModel.h"
#import "OADetailViewController.h"
#import "OADetailDisPatchController.h"
#import "OAUnDoneListCell.h"
#import "ckUnDonelistCell.h"
#import "dzggViewController.h"
@interface nbViewController ()
@property(nonatomic,strong)NSMutableArray * dataArray;
@property(nonatomic,assign)int totalCounts; //总条数
@property(nonatomic,assign)int currentPage; //当前页
@property(nonatomic,strong)NSDictionary * adic;
@end

@implementation nbViewController


- (void)viewDidLoad {
    [super viewDidLoad];
     _TableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
        self.TableView.separatorStyle = UITableViewCellSeparatorStyleNone;
          _TableView.separatorStyle = NO;

    self.TableView.delegate = self;
    self.TableView.dataSource =self;
    [self.view addSubview:_TableView];
        [self.TableView addHeaderWithCallback:^{
        self.currentPage = 1;

        [self loadData]; //加载网络数据
    }];
    [self.TableView headerBeginRefreshing];
    
    [self.TableView addFooterWithCallback:^{
        if ((self.currentPage - 1)*KPageSize < self.totalCounts ){
             [self loadMore];
        }else{
        
            [self.TableView footerEndRefreshing];
            [self.view makeToast:@"没有更多了"];
    
        }
       
    }];

    // Do any additional setup after loading the view.
}

-(void)refrshData{
    self.currentPage = 1;
    [self loadData]; //加载网络数据
}

-(NSMutableArray*)dataArray{
    if (_dataArray == nil) {
        _dataArray =   [NSMutableArray array];
    }
    return _dataArray;
}

#pragma mark 加载网络数据
-(void)loadData{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools requestWithURL:KexchgeneralURL arrays:array method:@"draftPage" success:^(id JSON) {
   // NSLog(@"%@",JSON);
        if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
        }
//        self.dataArray =  [self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]];
//        [self.tableView reloadData];
//        [self.tableView headerEndRefreshing];
//        self.currentPage++;
//        if (self.dataArray.count ==0) {
//            [self.view makeToast:@"暂时还没拟办工作哦"];
//        }

_dataArray =   [NSMutableArray array];
        NSArray *array = JSON[@"data"];
        self.totalCounts =[JSON[@"number"] intValue];
if(JSON[@"number"]){

       self.title = [NSString stringWithFormat:@"拟办工作(%@)",JSON[@"number"] ];}

       else{

       self.title = @"拟办工作";

       

       }      _adic= JSON[@"display"];
         for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
}
        [self.TableView reloadData];
        [self.TableView headerEndRefreshing];
        self.currentPage++;
        if (self.dataArray.count ==0) {
        [self.view makeToast:@"暂时还没有拟办工作哦"];
        }
    } failure:^(NSError *error) {
        [self.TableView headerEndRefreshing];
    }];
}
#pragma mark 加载更多
-(void)loadMore{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools requestWithURL:KexchgeneralURL arrays:array method:@"draftPage" success:^(id JSON) {
//        [self.dataArray addObjectsFromArray:[self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]]];
//        self.currentPage++;
//                [self.tableView reloadData];
//
//        [self.tableView footerEndRefreshing];
       NSArray *array = JSON[@"data"];
  for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    }
_adic= JSON[@"display"];
        self.currentPage++;
        [self.TableView reloadData];
        [self.TableView footerEndRefreshing];
    } failure:^(NSError *error) {
        [self.TableView footerEndRefreshing];
    }];
    
}


//得到服务器返回数据中的标题
//传参数：一个服务器返回的二进制数据
-(NSMutableArray*)getDataList:(NSData*)data
{
    NSMutableArray * array = [NSMutableArray array];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（<交换 >）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（数据）
    NSArray *dataArray= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement * elemtenData in dataArray) {
        NSArray * subElement = [elemtenData elementsForName:@"数据要素"];
        for (GDataXMLElement *data in subElement) {
            UnDoneModel * model = [[UnDoneModel alloc] init];
            GDataXMLElement * titleElement = [[data elementsForName:@"标题"] objectAtIndex:0];
            GDataXMLElement * timeElement = [[data elementsForName:@"时间"] objectAtIndex:0];
            GDataXMLElement * fileIdElement = [[data elementsForName:@"标识"] objectAtIndex:0];
            model.title = [titleElement stringValue];
            model.time = [timeElement stringValue];
            model.fileId = [fileIdElement stringValue];
            [array addObject:model];
        }
    }
    
    NSArray *countArray= [rootElement elementsForName:@"控制"];
    for (GDataXMLElement * data in countArray) {
        GDataXMLElement * countElement = [[data elementsForName:@"条数"] objectAtIndex:0];
        NSString * counts = [countElement stringValue];
        self.totalCounts = [counts intValue] ;
        
    }
    self.title = [NSString stringWithFormat:@"拟办工作(%d)",self.totalCounts];
    return array;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    UnDoneModel * model = self.dataArray[indexPath.row];
//    CGFloat height = 0;
//    CGFloat  titlesize  = [OAToolBox sizebyText:model.title font:14 minsWidth:65];
//
//    NSString * desstring = [NSString stringWithFormat:@"%@",model.time];
//    CGFloat dessize = [OAToolBox sizebyText:desstring font:13 minsWidth:60];;
//    height = titlesize + dessize + 20;
//    return  height;
NSDictionary *dic = self.dataArray[indexPath.row];

    CGFloat  titleFloat  = [OAToolBox sizebyText:dic[@"subject"] font:15 minsWidth:60];

    return  titleFloat  +75+10;

}




#pragma mark UITableView dataScource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
 NSString *CellIdentifier = @"Cell";
    ckUnDonelistCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
  if (cell==nil) {
        cell=[[ckUnDonelistCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
 NSDictionary *dic = self.dataArray[indexPath.row];
    cell.dic = dic;
        cell.adic = _adic;

    cell.number = [NSString stringWithFormat:@"%ld",(long)indexPath.row+1];
    return cell;

//    OAUnDoneListCell * cell = [OAUnDoneListCell cellWithTableView:tableView];
//    UnDoneModel * model = self.dataArray[indexPath.row];
//    cell.model = model;
//    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
       NSDictionary *dic = self.dataArray[indexPath.row];
 UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

     UnDoneModel * model = self.dataArray[indexPath.row];
detailViewController * detailVC = (detailViewController*)[storyBoard instantiateViewControllerWithIdentifier:@"detail"];

    detailVC.fileId = dic[@"unid"];

detailVC.type = @"niban";
detailVC.hidesBottomBarWhenPushed = YES;

[self.navigationController pushViewController:detailVC animated:YES];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}


@end

